package com.java2007.hotel.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.java2007.hotel.dao.FoodDao;
import com.java2007.hotel.entity.PageBean;
import com.java2007.hotel.factory.BeanFactory;
import com.java2007.hotel.pojo.Food;
import com.java2007.hotel.service.FoodService;
import com.java2007.hotel.utils.JdbcUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @author ghy
 * @version 1.0
 * @date 2021-01-22
 */
public class FoodServiceImpl implements FoodService {

    private FoodDao foodDao = (FoodDao) BeanFactory.getBean("com.java2007.hotel.dao.impl.FoodDaoImpl");


    @Override
    public int save(Food food) throws SQLException {

        try {
            JdbcUtil.begin();
            //由分转成元
            food.setPrice(food.getPrice() * 100);
            food.setVipPrice(food.getVipPrice() * 100);
            foodDao.save(food);

            JdbcUtil.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            JdbcUtil.rollback();
            return 0;
        }

        return 1;
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Food findById(int id) throws SQLException {
        return foodDao.findById(id);
    }

    /**
     * 分页
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PageBean<Food> findByPage(Integer pageNo, Integer pageSize) throws SQLException {

        //1.合理化 pageNo 和 pageSize
        if(pageNo < 0) {
            pageNo = 1;
        }

        //查询菜品数据
        List<Food> list = foodDao.findByPage((pageNo - 1) * pageSize, pageSize);
        //查询菜品数量
        Long count = foodDao.getCount();

        PageBean<Food> pageBean = new PageBean<>();
        //当前页
        pageBean.setPageNo(pageNo);
        //页面展示数据
        pageBean.setList(list);
        //总条数
        pageBean.setTotalCount(count);
        //总页数
        pageBean.setTotalPages();

        return pageBean;
    }
}
